package be.android.forap.gui;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import be.android.forap.ForAp;
import be.android.forap.R;
import be.android.forap.dataprovider.ContactManager;
import be.android.forap.dataprovider.RawContact;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DebugActivity extends Activity{

	protected static final String TAG = "DebugActivity";
	private ForAp app;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.debug);

		app  = ForAp.getInstance();

		test3();
		test2();
		//test3();






		/*TextView name = (TextView) findViewById(R.id.de_textView1);
		TextView password = (TextView) findViewById(R.id.de_textView2);
		TextView pubkey = (TextView) findViewById(R.id.de_textView3);
		TextView privkey = (TextView) findViewById(R.id.de_textView4);
		SharedPreferences settings = getSharedPreferences(forAp.FORAP_PREFS_NAME, MODE_PRIVATE);
		String user = settings.getString(forAp.FORAP_USER, "ERROR");
		String passphrase = settings.getString(forAp.FORAP_PASSWORD, "ERROR");
		String pub = settings.getString(forAp.FORAP_USER_PUBLICKEY, "ERROR");
		String priv = settings.getString(forAp.FORAP_USER_PRIVATEKEY, "ERROR");
		name.setText(user);
		password.setText(passphrase);
		pubkey.setText(pub);

		InputStream keyIn = new ByteArrayInputStream(pub.getBytes());
		PGPPublicKey key;
		try {
			//key = OpenPGP.readPublicKey(keyIn);
			privkey.setText(KeyUtil.readPublicKeyInfo(keyIn));
			keyIn.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PGPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}


	private void test3() {
		final ForAp app = ForAp.getInstance();
		final Context context = this;

		Button b1 = (Button)findViewById(R.id.debug_part3_button1);
		b1.setText("Force Sync");
		b1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/*final ContentResolver resolver = context.getContentResolver();
				/*final BatchOperation batchOperation = new BatchOperation(context, resolver);
				long id1 = ContactManager.lookupRawContact(resolver, 1);
				long id2 = ContactManager.lookupRawContact(resolver, 2);
				ContactManager.deleteContact(id1, batchOperation);
				ContactManager.deleteContact(id2, batchOperation);
				batchOperation.execute();
				Log.d(TAG, "ID old: " + id1 + " new: "+  ContactManager.lookupRawContact(resolver, 1));
				Log.d(TAG, "ID old: " + id2 + " new: "+  ContactManager.lookupRawContact(resolver, 2));*/
				Log.d(TAG, "FORCE SYNC");
				AccountManager am = AccountManager.get(context);
				Account[] accounts = am.getAccountsByType(context.getString(R.string.ACCOUNT_TYPE));
				for(int i=0;i<accounts.length;i++){
					Log.d(TAG, "Account name: " + accounts[i].name + " type: "+ accounts[i].type);
				}
				Bundle bundle = new Bundle();
				bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
				bundle.putBoolean(ContentResolver.SYNC_EXTRAS_FORCE, true);
				bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
				ContentResolver.requestSync(accounts[0], ContactsContract.AUTHORITY, bundle);
			}
		});

	//	final long globalID = RawContact.generateUniqueGlobalID(context, app.getUser());

		Button b2 = (Button)findViewById(R.id.debug_part3_button2);
		b2.setText("Add Contact");
		b2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				
				//long globalID = RawContact.generateUniqueGlobalID(context, app.getUser());
		//		Toast.makeText(getApplicationContext(), "ID: " + globalID, Toast.LENGTH_LONG).show();
			//	RawContact rc = RawContact.createNewContact("", "johnny"+globalID, "doe", "0479502136", "a@a.c", app.getPublicKey(), false, 0, globalID);
		//		ContactManager.addNewContact(context, app.getUser(), rc);
		//		long globalID2 = RawContact.generateUniqueGlobalID(context, app.getUser());
		//		Toast.makeText(getApplicationContext(), "ID: " + globalID2, Toast.LENGTH_LONG).show();
	//			RawContact rc2 = RawContact.createNewContact("", "jantje", "doe", "0479502136", "a@a.c", app.getPublicKey(), false, 0, globalID2);
			//	ContactManager.addNewContact(context, app.getUser(), rc2);
			}
		});

		Button b3 = (Button)findViewById(R.id.debug_part3_button3);
		b3.setText("Delete Contact");
		b3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
			//	ContactManager.deleteContact(context, globalID);
			}
		});

		Button b4 = (Button)findViewById(R.id.debug_part3_button4);
		b4.setText("Show 3rd party contacts");
		b4.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AccountManager am = AccountManager.get(context);
				Account[] accounts = am.getAccountsByType(context.getString(R.string.ACCOUNT_TYPE));
				ContactManager.setAccountContactsVisibility(context, accounts[0], true);
				/*RawContact nc = RawContact.createNewContact("", "johnny", "", "", "", "", false, 0, globalID);
				ContactManager.updateContact(context, globalID, nc);*/
			}
		});


		Button b5 = (Button)findViewById(R.id.debug_part3_button5);
		b5.setText("get dirty contacts");
		b5.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AccountManager am = AccountManager.get(context);
				Account[] accounts = am.getAccountsByType(context.getString(R.string.ACCOUNT_TYPE));
				//Toast.makeText(getApplicationContext(), "account name: " + accounts[0].name + " ?= " + app.getUser(), Toast.LENGTH_LONG).show();
				
				List<RawContact> dl = ContactManager.getDirtyContacts(context,  accounts[0]);
				String out = "Dirty(" + dl.size() + "): ";
				for(RawContact c : dl){
					out = out + c.getBestName() + ":" + c.getGlobalContactId() + " ";
				}
				TextView outView = (TextView) findViewById(R.id.debug_part3_output5);
				outView.setText(out);
				
			}
		});


		Button b6 = (Button)findViewById(R.id.debug_part3_button6);
		b6.setText("manual Download");
		b6.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/*try{
					//DOWNLOAD CONTACTS
					DropboxFileInfo downloadInfo;
					ByteArrayOutputStream downloadStream = new ByteArrayOutputStream();
					downloadInfo = DropboxUtil.downloadContacts(downloadStream);				
					final String downloadContents = new String(downloadStream.toByteArray());

					JSONArray serverJsonContacts = new JSONArray(downloadContents);
					ArrayList<RawContact> serverContacts = new ArrayList<RawContact>();
					for (int i = 0; i < serverJsonContacts.length(); i++) {
						RawContact rawContact = RawContact.valueOf(serverJsonContacts.getJSONObject(i));
						if (rawContact != null) {
							serverContacts.add(rawContact);
						}
					}
					
					TextView out = (TextView) findViewById(R.id.debug_part3_output6);
					out.setText(serverContacts.get(0).getBestName() + " " + serverContacts.get(1).getBestName());
					
				} catch (DropboxException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
			}
		});
		
		Button b7 = (Button)findViewById(R.id.debug_part3_button7);
		b7.setText("get deleted contacts");
		b7.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				AccountManager am = AccountManager.get(context);
				Account[] accounts = am.getAccountsByType(context.getString(R.string.ACCOUNT_TYPE));
				
				List<RawContact> dl = ContactManager.getAllContacts(context,  accounts[0].name);
				String out = "Deleted: ";
				for(RawContact c : dl){
					if(c.isDeleted()){
						out = out + c.getBestName() + ":" + c.getGlobalContactId() + " ";
					}
				}
				TextView outView = (TextView) findViewById(R.id.debug_part3_output7);
				outView.setText(out);
				
			}
		});



		/*ForAp app = ForAp.getInstance();
		long globalID = 1338;
		RawContact rc = RawContact.createNewContact("", "johnny", "doe", "0479502136", "a@a.c", app.getPublicKey(), false, 0, globalID);

		//long globalID = 1337;//RawContact.generateUniqueGlobalID(this, app.getUser());
		//RawContact rc = RawContact.createNewContact("", "john", "doe", "0479502136", "a@a.c", app.getPublicKey(), false, 0, globalID);
		ContactManager.addNewContact(this, app.getUser(), rc);*/
	}

	private void showInputBox() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Input");

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String value = input.getText().toString();
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		alert.show();
		/*ForAp app = ForAp.getInstance();
		long globalID = 1337;
		ContactManager.deleteContact(this, globalID );*/
		/*ForAp app = ForAp.getInstance();
		long globalID = RawContact.generateUniqueGlobalID(this, app.getUser());
		RawContact rc = RawContact.createNewContact("", "iris", "ver", "0479502136", "a@a.c", app.getPublicKey(), false, 0, 0);
		ContactManager.addNewContact(this, app.getUser(), rc);*/
	}


	private void test2() {

		Button saveState = (Button) findViewById(R.id.debug_part2_button1);
		final TextView saveOutput = (TextView) findViewById(R.id.debug_part2_output1);
		Button checkState = (Button) findViewById(R.id.debug_part2_button2);
		final TextView checkOutput = (TextView) findViewById(R.id.debug_part2_output2);
		final String FILENAME = "debug_test2";

		try{
			//Read file in Internal Storage
			FileInputStream fis;
			String content = "";
			fis = openFileInput(FILENAME);
			byte[] input = new byte[fis.available()];
			while (fis.read(input) != -1) {}
			content += new String(input);
			Toast.makeText(getApplicationContext(), "Previous State", Toast.LENGTH_LONG).show();
			saveOutput.setText(content.toString());
		} catch (FileNotFoundException e1) {
			// No state saved
			saveOutput.setText("No state saved.");
			Toast.makeText(getApplicationContext(), "No state saved", Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		saveState.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {
					String content = app.getPrivateKey();
					FileOutputStream fos;
					fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
					fos.write(content.getBytes());
					fos.close();
					saveOutput.setText(content);
					Toast.makeText(getApplicationContext(), "State Saved", Toast.LENGTH_LONG).show();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		checkState.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String prev = saveOutput.getText().toString(); 
				if(prev.equals(app.getPrivateKey())){
					checkOutput.setText("Test Successfull");
				} else {
					checkOutput.setText("Test Failed");
				}
			}
		});

	}

	public void actionup(){
		//DropboxUtil.uploadContentInFile("test", "name");
		//Intent download = new Intent(getApplicationContext(), DownloadActivity.class);
		//download.putExtra(DownloadActivity.DOWNLOAD_PATH, "https://www.dropbox.com/s/bvw83c8lzflkc3e/John%20doe.txt?dl=1");
		//download.putExtra(DownloadActivity.DOWNLOAD_PATH, "http://db.tt/NW9lx2ZF");
		//startActivity(download);

		//RawContact dirty = new RawContact("","name", "John doe", "john", "doe", "0479502136", "", "", "a@a.c", "pub", false, 0, 0, 0, true);
		//NetworkUtil.uploadDirtyContacts(dirty,this);

		/*String error = null;
		List<String> mSearchResult = null;
		KeyServerUtil server = new KeyServerUtil();
		SharedPreferences settings = getSharedPreferences(forAp.FORAP_PREFS_NAME, MODE_PRIVATE);
		String user = settings.getString(forAp.FORAP_USER, "");
		String passphrase = settings.getString(forAp.FORAP_PASSWORD, "");
		String pub = settings.getString(forAp.FORAP_USER_PUBLICKEY, "");
		try {
			mSearchResult = server.getKeyFromServer(user);

        } catch (QueryException e) {
            error = "" + e;
        } catch (InsufficientQuery e) {
            error = "Insufficient query.";
        } catch (TooManyResponses e) {
            error = "Too many responses.";
        }

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select output method");
		builder.setIcon(R.drawable.icon);
		builder.setItems((CharSequence[]) mSearchResult.toArray(), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int index) {
				//selectedOutput = index;
				//processOutput(selectedOutput);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();*/



	}
	public void actionsync(){
		if(isDownloadManagerAvailable()){
			/*String url = "https://www.dropbox.com/s/bvw83c8lzflkc3e/John%20doe.txt?dl=1";
			DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
			request.setDescription("Some descrition");
			request.setTitle("Some title");
			// in order for this if to run, you must use the android 3.2 to compile your app

			   // request.allowScanningByMediaScanner();
			    //request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

			request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");

			// get download service and enqueue file
			DownloadManager manager = (DownloadManager) getSystemService(getApplication().DOWNLOAD_SERVICE);
			manager.enqueue(request);*/
		}else{
			Toast.makeText(getApplicationContext(), "no downloadmanger", Toast.LENGTH_SHORT).show();
		}


		/*SharedPreferences settings = getSharedPreferences(forAp.FORAP_PREFS_NAME, MODE_PRIVATE);
		String user = settings.getString(forAp.FORAP_USER, "");
		String passphrase = settings.getString(forAp.FORAP_PASSWORD, "");
		String pub = settings.getString(forAp.FORAP_USER_PUBLICKEY, "");

		KeyServerUtil server = new KeyServerUtil();
		try {
			server.uploadKeyToServer(pub);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

		/*RawContact dirty = new RawContact("","name", "John doe", "john", "doe", "0479502136", "", "", "a@a.c", "pub", false, 0, 0, 0, true);
		List<RawContact> dirtyList = new ArrayList<RawContact>();
		dirtyList.add(dirty);
        try {
			NetworkUtil.syncContacts(this, 0, dirtyList);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}

	private boolean isDownloadManagerAvailable() {
		/*try {
	        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
	            return false;
	        }
	        Intent intent = new Intent(Intent.ACTION_MAIN);
	        intent.addCategory(Intent.CATEGORY_LAUNCHER);
	        intent.setClassName("com.android.providers.downloads.ui", "com.android.providers.downloads.ui.DownloadList");
	        List<ResolveInfo> list = getApplication().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
	        return list.size() > 0;
	    } catch (Exception e) {*/
		return false;
		//}*/
	}

}


